package cn.ilikes.tools.nosql.jpa.springs;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import cn.ilikes.tools.nosql.jpa.persistences.IJPASQLEntityManager;
import cn.ilikes.tools.nosql.jpa.query.pages.PageEntitys;

public abstract class BEntrtyManager {

	public abstract IJPASQLEntityManager getEntityManager();

	protected Query hsqlQuery(String HSQL) {

		EntityManager entityManager = getEntityManager();
		return entityManager.createQuery(HSQL);
	}

	protected Query createNamedQuery(String QueryName) {

		EntityManager entityManager = getEntityManager();
		return entityManager.createNamedQuery(QueryName);
	}

	protected PageEntitys excPageQuery(Query query, Map<String, Object> values, int size) throws SpringErrorException {

		if (values != null) {
			for (Iterator<Entry<String, Object>> entrys = values.entrySet().iterator(); entrys.hasNext();) {
				Entry<String, Object> entry = entrys.next();
				Object value = entry.getValue();
				query.setParameter(entry.getKey(), value);
			}
		}
		query.setMaxResults(size);
		return (PageEntitys) query.getSingleResult();
	}

	protected <T> List<T> excQuery(Query query, Map<String, Object> values, int... rowsAndSize) throws SpringErrorException {

		if (values != null) {
			for (Iterator<Entry<String, Object>> entrys = values.entrySet().iterator(); entrys.hasNext();) {
				Entry<String, Object> entry = entrys.next();
				Object value = entry.getValue();
				query.setParameter(entry.getKey(), value);
			}
		}
		int leght = rowsAndSize.length;
		if (leght > 0) {
			if (leght == 1) {
				int first = rowsAndSize[0];
				if (first < 0)
					throw new SpringErrorException(" find sql First Result  < 0 ");
				query.setFirstResult(rowsAndSize[0]);
			} else if (leght == 2) {
				int first = rowsAndSize[0];
				int max = rowsAndSize[1];
				if (first < 0 || max < 0)
					throw new SpringErrorException(" find sql First Result  < 0  or max <0");
				query.setFirstResult(first);
				query.setMaxResults(max);
			} else if (leght > 2)
				throw new SpringErrorException(" find sql First  leght ==2  ;first is  start ;  ");
		}

		return query.getResultList();
	}

	protected Object exceteSingleQuery(Query query, Map<String, Object> values) {

		if (values != null) {
			for (Iterator<Entry<String, Object>> entrys = values.entrySet().iterator(); entrys.hasNext();) {
				Entry<String, Object> entry = entrys.next();
				Object value = entry.getValue();
				query.setParameter(entry.getKey(), value);
			}
		}

		return query.getSingleResult();
	}
}
